import { useState, useEffect } from 'react';
import CodeMirror from '@uiw/react-codemirror';
import { python } from '@codemirror/lang-python';
import { githubDark } from '@uiw/codemirror-theme-github';
import { Button, message, Space, Input, Layout, Card, Typography } from 'antd';
import { useNavigate, useLocation } from 'react-router-dom';
import { ExpandOutlined, ShrinkOutlined, SaveOutlined, ArrowLeftOutlined } from '@ant-design/icons';
import { toolService } from '../services/tool.service';

const { Content } = Layout;
const { Title } = Typography;

interface EditorProps {
  initialContent: string;
  toolId?: string | null;
  onSaved?: () => void;
  onBack?: () => void;
}

export default function CodeEditor({ initialContent, toolId, onSaved, onBack }: EditorProps) {
  const [code, setCode] = useState(initialContent);
  const [tool_name, setName] = useState('');
  const [loading, setLoading] = useState(false);
  const [isFullscreen, setIsFullscreen] = useState(false);
  const location = useLocation();
  const navigate = useNavigate();

  const positionStyle = isFullscreen ? 'fixed' : 'relative';
  
  const containerStyle = {
    width: isFullscreen ? '100vw' : '100%',
    height: isFullscreen ? '100vh' : '700px',
    display: 'flex',
    flexDirection: 'column' as const,
    boxShadow: '0 2px 4px rgba(0, 0, 0, 0.1)',
    position: positionStyle as 'fixed' | 'relative',
    top: isFullscreen ? 0 : 'auto',
    left: isFullscreen ? 0 : 'auto',
    zIndex: isFullscreen ? 1000 : 'auto',
    backgroundColor: (githubDark as any).settings?.background || '#0d1117'
  };

  useEffect(() => {
    const id = toolId || new URLSearchParams(location.search).get('tool_id');
    
    if (id) {
      const loadCode = async () => {
        try {
          setLoading(true);
          const response = await toolService.fetchCode(id);
          setCode(response.content);
          setName(response.tool_name);
        } catch (err: unknown) {
          message.error(err instanceof Error ? err.message : '加载代码失败');
        } finally {
          setLoading(false);
        }
      };
      loadCode();
    }
  }, [toolId, location.search]);

  const handleSave = async () => {
    try {
      setLoading(true);
      const id = toolId || new URLSearchParams(location.search).get('tool_id');
      await toolService.saveTool({
        tool_id: id || undefined,
        tool_name: tool_name,
        content: code
      });
      message.success(id ? '代码已更新' : '代码已保存');
      
      if (onSaved) {
        onSaved();
      }
    } catch (err: unknown) {
      message.error(err instanceof Error ? err.message : '保存异常');
    } finally {
      setLoading(false);
    }
  };

  const handleBack = () => {
    if (onBack) {
      onBack();
    } else {
      navigate('/dev_tools/code-list');
    }
  };

  return (
    <Layout className="site-layout">
      <Content style={{ margin: '0 16px', padding: 24, minHeight: 280 }}>
        <Card bordered={false}>
          <div style={{ 
            marginBottom: 16, 
            display: 'flex',
            justifyContent: 'space-between',
          }}>
            <Space>
              <Button 
                icon={<ArrowLeftOutlined />} 
                onClick={handleBack}
              >
                返回列表
              </Button>
              <Button 
                icon={isFullscreen ? <ShrinkOutlined /> : <ExpandOutlined />}
                onClick={() => setIsFullscreen(!isFullscreen)}
              />
              <Input 
                placeholder="输入代码名称"
                value={tool_name}
                onChange={(e) => setName(e.target.value)}
                style={{ width: 200 }}
              />
            </Space>
            
            <Button 
              type="primary"
              icon={<SaveOutlined />}
              loading={loading}
              onClick={handleSave}
            >
              保存代码
            </Button>
          </div>
          <div style={containerStyle}>
            <CodeMirror
              value={code}
              width="100%"
              height="100%"
              theme={githubDark}
              extensions={[python()]}
              onChange={setCode}
              basicSetup={{
                lineNumbers: true,
                highlightActiveLineGutter: true,
                foldGutter: true,
                autocompletion: true,
              }}
              style={{ 
                flex: 1,
                overflow: 'auto',
                minHeight: '400px'
              }}
            />
          </div>
        </Card>
      </Content>
    </Layout>
  );
}